package com.wzh.mysending.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.wzh.mysending.R;
import com.wzh.mysending.adapter.UserAdapter;
import com.wzh.mysending.base.BaseActivity;
import com.wzh.mysending.config.Constant;
import com.wzh.mysending.model.LocationEntity;
import com.wzh.mysending.model.UserEntity;
import com.wzh.mysending.service.KeepService;
import com.wzh.mysending.service.MainService;
import com.wzh.mysending.utils.loc.LocationUtil;
import com.wzh.mysending.utils.loc.OnGetLocationChanged;
import com.wzh.mysending.utils.view.XCRoundImageView;
import com.wzutils.NetUtils;
import com.wzutils.SPUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener, OnGetLocationChanged, BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.nav_view)
    NavigationView navigationView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;
    UserAdapter userAdapter;
    @BindView(R.id.my_rec)
    RecyclerView myRec;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    private int limit = 10;        // 每页的数据是10条
    private int curPage = 0;        // 当前页的编号，从0开始
    LocationUtil locationUtil;
    double lat, lot;
    Intent intent;
    Bundle bundle;
    private View headerView;
    TextView user_name, user_phone;
    private XCRoundImageView imageView;
    public static MainActivity instance = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        intitView();
        initEvent();

    }

    private void initEvent() {
        navigationView.setNavigationItemSelectedListener(this);
        myRec.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                bundle.putSerializable(Constant.USER_ENTITY, (UserEntity) adapter.getItem(position));
                bundle.putDouble(Constant.LAT, lat);
                bundle.putDouble(Constant.LOT, lot);
                intent.putExtras(bundle);
                intent.setClass(context, LocMapActivity.class);
                startActivity(intent);
            }
        });
        mySwf.setOnRefreshListener(this);
    }

    private void intitView() {
        instance = this;
        intent = getIntent();
        bundle = intent.getExtras();
        if (bundle == null) {
            bundle = new Bundle();
        }
        initHeard();
        if (NetUtils.isConnected(context)) {
            setUser();
        }
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        setRefresh(mySwf);
        initAdapter();
        MainActivityPermissionsDispatcher.onNeedWithCheck(this);
    }

    private void setUser() {
        BmobQuery<UserEntity> userEntityBmobQuery = new BmobQuery<>();
        userEntityBmobQuery.getObject(String.valueOf(get(Constant.USER_ID, "")), new QueryListener<UserEntity>() {
            @Override
            public void done(UserEntity userEntity, BmobException e) {
                if (e == null) {
                    if (userEntity != null) {
                        tvTitle.setText(userEntity.getUserName());
                        user_name.setText(userEntity.getUserName());
                        user_phone.setText(userEntity.getUserPhone());
                        setImage(userEntity.getUser_img(), imageView);
                    }
                }

            }
        });
    }

    private void initHeard() {
        headerView = navigationView.getHeaderView(0);
        user_name = $(R.id.user_name, headerView);
        user_phone = $(R.id.user_phone, headerView);
        imageView = $(R.id.imageView, headerView);

    }

    private void addData() {
        if (locationUtil != null) {
            locationUtil.stopLocation();
        }
        userAdapter.setLatAndLot(lat, lot);
        BmobQuery<UserEntity> userEntityBmobQuery = new BmobQuery<>();
        userEntityBmobQuery.order("-updatedAt");
        userEntityBmobQuery.setLimit(limit);
        if (curPage != 0) {
            userEntityBmobQuery.setSkip(curPage * limit);
        } else {
            userEntityBmobQuery.setSkip(curPage);
        }
        userEntityBmobQuery.include("locationEntity");
        userEntityBmobQuery.findObjects(new FindListener<UserEntity>() {
            @Override
            public void done(List<UserEntity> list, BmobException e) {
                mySwf.setRefreshing(false);
                if (e == null) {
                    Log.e("查询成功：共", list.size() + "条数据。");
                    Log.e("查询成功：", list.toString());
                    if (curPage == 0) {
                        userAdapter.setNewData(list);
                    } else {
                        userAdapter.addData(list);
                    }
                    if (list.size() != 10) {
                        userAdapter.loadMoreEnd(false);
                    } else {
                        userAdapter.loadMoreComplete();
                        curPage++;
                    }
                } else {
                    toast("查询失败，请稍后重试。");
                }
            }
        });

    }

    private void initAdapter() {
        setRecy(myRec);
        userAdapter = new UserAdapter(R.layout.item_user, new ArrayList<UserEntity>(), context);
        userAdapter.setEmptyView(emptyView);
        userAdapter.setOnLoadMoreListener(this, myRec);
        userAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        myRec.setAdapter(userAdapter);
    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationUtil != null) {
            locationUtil.destroyLocation();
        }
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_set) {
            intent.setClass(context, SettingActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_out) {

            showWarron();


        } else if (id == R.id.nav_about) {
            intent.setClass(context, AboutActivity.class);
            startActivity(intent);
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    private void showWarron() {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(context);
        normalDialog.setIcon(R.mipmap.logo);
        normalDialog.setTitle("提示：确定要退出吗？");
        normalDialog.setMessage("退出后无法再上传定位");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do

                        intent.setClass(context, MainService.class);

                        stopService(intent);
                        intent.setClass(context, KeepService.class);
                        stopService(intent);
                        SPUtils.clear(context);
                        intent.setClass(context, LonginActivity.class);
                        startActivity(intent);
                        finish();

                    }
                });
        normalDialog.setNegativeButton("算了",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do

                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();

    }


    @Override
    public void onLocationOk(AMapLocation aMapLocation) {
        Log.e("OK==", aMapLocation.toString());
        lat = aMapLocation.getLatitude();
        lot = aMapLocation.getLongitude();
        addData();
    }

    @Override
    public void onLocationError(AMapLocation aMapLocation) {
        Log.e("onLocationError==", aMapLocation.toString());
        toast("获取定位信息失败，距离显示不准确");
        lat = 0;
        lot = 0;
        addData();
    }

    @Override
    public void onLocationNull(AMapLocation aMapLocation) {
        Log.e("onLocationNull==", aMapLocation.toString());
        toast("获取定位信息失败，距离显示不准确");
        lat = 0;
        lot = 0;
        addData();
    }

    @Override
    public void onLoadMoreRequested() {
        addData();
    }

    @Override
    public void onRefresh() {
        limit = 10;        // 每页的数据是10条
        curPage = 0;        // 当前页的编号，从0开始
        if (locationUtil != null) {
            locationUtil.startLocation();
        } else {
            locationUtil = new LocationUtil(getApplicationContext(), this);
            locationUtil.startLocation();
        }

    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onNeed() {
        locationUtil = new LocationUtil(getApplicationContext(), this);
        locationUtil.startLocation();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onShow(final PermissionRequest request) {
        request.proceed();
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onPermiss() {
        toast("请授权许可，否则无法运行");
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onNever() {
        toast("请授权许可，否则无法运行");
    }
}
